<template>
    <div class="simulation-container">
      <div ref="rendererContainer" class="renderer-canvas"></div>
      <div class="controls">
        <button @click="toggleAnimation">{{ isPlaying ? '暂停' : '播放' }}</button>
        <input type="range" min="0" :max="trajectoryLength" v-model="currentIndex" step="1">
        <span>速度: </span>
        <input type="range" min="1" max="20" v-model="animationSpeed">
      </div>
      <div class="stats">
        <span>帧率: {{ fps }} FPS</span> | 
        <span>轨迹点: {{ trajectoryLength }}</span> | 
        <span>内存: {{ memoryUsage }} MB</span>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
  import * as THREE from 'three';
  import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  import Stats from 'three/addons/libs/stats.module.js';
  
  // 模拟轨迹数据（实际应用中从API获取）
  const generateTrajectoryData = (count = 50000) => {
    const positions = new Float32Array(count * 3);
    for (let i = 0; i < count; i++) {
      const t = i / 1000;
      positions[i * 3] = 50 * Math.sin(t * 2);     // X
      positions[i * 3 + 1] = 20 * Math.cos(t * 1.5); // Y
      positions[i * 3 + 2] = 30 * Math.sin(t * 0.8); // Z
    }
    return positions;
  };
  
  const rendererContainer = ref(null);
  const isPlaying = ref(true);
  const currentIndex = ref(0);
  const animationSpeed = ref(5);
  const fps = ref(0);
  const memoryUsage = ref(0);
  
  // 核心Three.js对象
  let scene, camera, renderer, controls, stats;
  let toolInstance, trajectoryLine, workpieceMesh;
  const trajectoryData = generateTrajectoryData(80000);
  const trajectoryLength = Math.floor(trajectoryData.length / 3);
  
  // 初始化场景
  const initScene = () => {
    // 创建场景
    scene = new THREE.Scene();
    scene.background = new THREE.Color(0x1a1a1a);
    scene.fog = new THREE.Fog(0x1a1a1a, 100, 300);
  
    // 创建相机
    camera = new THREE.PerspectiveCamera(
      60, 
      rendererContainer.value.clientWidth / rendererContainer.value.clientHeight, 
      0.1, 
      1000
    );
    camera.position.set(100, 100, 150);
  
    // 创建渲染器（开启抗锯齿和性能优化）
    renderer = new THREE.WebGLRenderer({ 
      antialias: true,
      powerPreference: 'high-performance'
    });
    renderer.setSize(
      rendererContainer.value.clientWidth, 
      rendererContainer.value.clientHeight
    );
    renderer.setPixelRatio(window.devicePixelRatio);
    rendererContainer.value.appendChild(renderer.domElement);
  
    // 添加轨道控制器
    controls = new OrbitControls(camera, renderer.domElement);
    controls.enableDamping = true;
  
    // 添加性能监控
    stats = new Stats();
    stats.dom.style.position = 'absolute';
    stats.dom.style.top = '0';
    rendererContainer.value.appendChild(stats.dom);
  
    // 添加光源
    const ambientLight = new THREE.AmbientLight(0x404040, 2);
    scene.add(ambientLight);
    
    const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
    directionalLight.position.set(1, 1, 1);
    scene.add(directionalLight);
  
    // 创建工件模型
    createWorkpiece();
    
    // 创建刀具模型
    createTool();
    
    // 创建轨迹线
    createTrajectoryLine();
    
    // 添加坐标轴辅助
    const axesHelper = new THREE.AxesHelper(50);
    scene.add(axesHelper);
  };
  
  // 创建工件模型
  const createWorkpiece = () => {
    const geometry = new THREE.BoxGeometry(80, 40, 60);
    const material = new THREE.MeshPhongMaterial({ 
      color: 0x4477aa,
      wireframe: true
    });
    
    workpieceMesh = new THREE.Mesh(geometry, material);
    workpieceMesh.position.set(0, 20, 0);
    scene.add(workpieceMesh);
  };
  
  // 创建刀具实例化模型（高性能）
  const createTool = () => {
    // 刀具几何体（简化模型）
    const toolGeometry = new THREE.CylinderGeometry(2, 2, 20, 12);
    const toolMaterial = new THREE.MeshPhongMaterial({ 
      color: 0xff6600 
    });
    
    // 使用InstancedMesh实现高性能实例化
    toolInstance = new THREE.InstancedMesh(toolGeometry, toolMaterial, 1);
    
    // 初始位置
    const matrix = new THREE.Matrix4();
    toolInstance.setMatrixAt(0, matrix);
    toolInstance.instanceMatrix.needsUpdate = true;
    
    scene.add(toolInstance);
  };
  
  // 创建轨迹线（使用BufferGeometry优化性能）
  const createTrajectoryLine = () => {
    // 仅显示部分轨迹点（性能优化）
    const visiblePoints = Math.min(5000, trajectoryLength);
    const positions = new Float32Array(visiblePoints * 3);
    
    for (let i = 0; i < visiblePoints; i++) {
      const index = Math.floor(i * trajectoryLength / visiblePoints);
      positions[i * 3] = trajectoryData[index * 3];
      positions[i * 3 + 1] = trajectoryData[index * 3 + 1];
      positions[i * 3 + 2] = trajectoryData[index * 3 + 2];
    }
    
    const geometry = new THREE.BufferGeometry();
    geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
    
    const material = new THREE.LineBasicMaterial({ 
      color: 0x00ff88,
      transparent: true,
      opacity: 0.5
    });
    
    trajectoryLine = new THREE.Line(geometry, material);
    scene.add(trajectoryLine);
  };
  
  // 更新刀具位置
  const updateToolPosition = (index) => {
    if (index >= trajectoryLength) return;
    
    const x = trajectoryData[index * 3];
    const y = trajectoryData[index * 3 + 1];
    const z = trajectoryData[index * 3 + 2];
    
    const matrix = new THREE.Matrix4();
    matrix.makeTranslation(x, y, z);
    
    // 根据轨迹方向旋转刀具（简化版）
    if (index < trajectoryLength - 1) {
      const nextX = trajectoryData[(index + 1) * 3];
      const nextY = trajectoryData[(index + 1) * 3 + 1];
      const nextZ = trajectoryData[(index + 1) * 3 + 2];
      
      const direction = new THREE.Vector3(
        nextX - x,
        nextY - y,
        nextZ - z
      ).normalize();
      
      const up = new THREE.Vector3(0, 1, 0);
      const axis = new THREE.Vector3().crossVectors(up, direction).normalize();
      const angle = Math.acos(up.dot(direction));
      
      const rotationMatrix = new THREE.Matrix4().makeRotationAxis(axis, angle);
      matrix.multiply(rotationMatrix);
    }
    
    toolInstance.setMatrixAt(0, matrix);
    toolInstance.instanceMatrix.needsUpdate = true;
  };
  
  // 动画循环
  let animationFrameId = null;
  const animate = () => {
    if (isPlaying.value) {
      currentIndex.value = (currentIndex.value + animationSpeed.value) % trajectoryLength;
    }
    
    updateToolPosition(Math.floor(currentIndex.value));
    
    // 更新工件切削效果（简化版）
    if (workpieceMesh) {
      const toolPos = new THREE.Vector3(
        trajectoryData[Math.floor(currentIndex.value) * 3],
        trajectoryData[Math.floor(currentIndex.value) * 3 + 1],
        trajectoryData[Math.floor(currentIndex.value) * 3 + 2]
      );
      
      // 这里可以添加更复杂的切削效果算法
    }
    
    controls.update();
    renderer.render(scene, camera);
    stats.update();
    
    // 更新性能数据
    fps.value = Math.round(stats.fps);
    memoryUsage.value = (performance.memory.usedJSHeapSize / (1024 * 1024)).toFixed(1);
    
    animationFrameId = requestAnimationFrame(animate);
  };
  
  // 切换动画状态
  const toggleAnimation = () => {
    isPlaying.value = !isPlaying.value;
  };
  
  // 响应窗口大小变化
  const onWindowResize = () => {
    camera.aspect = rendererContainer.value.clientWidth / rendererContainer.value.clientHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(
      rendererContainer.value.clientWidth, 
      rendererContainer.value.clientHeight
    );
  };
  
  // 监听轨迹索引变化
  watch(currentIndex, (newIndex) => {
    updateToolPosition(Math.floor(newIndex));
  });
  
  // 组件挂载时初始化
  onMounted(() => {
    initScene();
    animate();
    window.addEventListener('resize', onWindowResize);
  });
  
  // 组件卸载时清理
  onBeforeUnmount(() => {
    cancelAnimationFrame(animationFrameId);
    window.removeEventListener('resize', onWindowResize);
    
    if (renderer) {
      renderer.dispose();
      renderer.forceContextLoss();
    }
  });
  </script>
  
  <style scoped>
  .simulation-container {
    position: relative;
    width: 100%;
    height: 100vh;
    overflow: hidden;
  }
  
  .renderer-canvas {
    width: 100%;
    height: 100%;
  }
  
  .controls {
    position: absolute;
    bottom: 20px;
    left: 20px;
    background: rgba(0, 0, 0, 0.7);
    padding: 10px;
    border-radius: 8px;
    display: flex;
    gap: 15px;
    align-items: center;
  }
  
  .controls button {
    padding: 6px 12px;
    background: #4CAF50;
    border: none;
    border-radius: 4px;
    color: white;
    cursor: pointer;
  }
  
  .controls input[type="range"] {
    width: 200px;
  }
  
  .stats {
    position: absolute;
    top: 10px;
    right: 10px;
    background: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 8px;
    border-radius: 4px;
    font-family: monospace;
  }
  </style>